package com.heroCW.bodhiAttic.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heroCW.bodhiAttic.entity.User;
import com.heroCW.bodhiAttic.resultUtil.Result;
import com.heroCW.bodhiAttic.resultUtil.ResultCode;
import com.heroCW.bodhiAttic.service.UserService;
import com.heroCW.bodhiAttic.utils.SMSUtils;
import com.heroCW.bodhiAttic.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
        // 获取手机号
        String phone = user.getPhone();
        log.info("phone: {}", phone);

        if (StringUtils.isNotEmpty(phone)) {
            // 生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code: {}", code);

            // 调用阿里云提供的短信api完成发送短信
            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);

            // 需要将生成的验证码保存到session
            session.setAttribute(phone, code);

            return Result.success(ResultCode.SEND_MESSAGE_SUCCESS, "手机验证码短信发送成功");
        }

        return Result.error(ResultCode.SEND_MESSAGE_ERROR, "短信验证发送失败");
    }

    /**
     * 移动端用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map<String, Object> map, HttpSession session) {
        log.info("map: {}", map.toString());

        // 获取手机号
        String phone = map.get("phone").toString();

        // 获取验证码
        String code = map.get("code").toString();

        String codeInSession = "";
        // 从session中获取已保存的验证码
        if (session.getAttribute(phone)!=null) {
            codeInSession = session.getAttribute(phone).toString();
        }  else {
            return Result.error(ResultCode.SEND_MESSAGE_OVERDUE, "请再次发送验证码");
        }


        // 进行验证码的比对
        if (codeInSession.equals(code)) {
            // 比对成功，则登录成功

            User user = userService.getOneByPhone(phone);

            if (user == null) {
                // 判断当前手机号对应的用户是否为新用户，是则自动注册
                user = userService.saveUser(phone);
            }

            if (user.getStatus() == 0) {
                return Result.error(ResultCode.USER_LOGIN_ERROR, "您已被禁用，登录失败");
            }

            session.setAttribute("user", user.getId());
            return Result.success(ResultCode.USER_LOGIN_SUCCESS, user);

        }
        return Result.error(ResultCode.USER_LOGIN_ERROR, "验证码不匹配，登录失败");
    }

    /**
     * 用户登出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return Result.success(ResultCode.USER_LOGOUT_SUCCESS, "退出成功");
    }

    /**
     * 根据手机号查询用户
     *
     * @param phone
     * @return
     */
    @GetMapping("/p{phone}")
    public Result<User> getOneByPhone(@PathVariable String phone) {
        log.info("phone: {}", phone);

        User user = userService.getOneByPhone(phone);
        log.info("user: {}", user);


        return Result.success(user);
    }

    /**
     * 根据Id查询用户
     *
     * @param id
     * @return
     */
    @GetMapping("/u{id}")
    public Result<User> getOneById(@PathVariable Long id) {
        log.info("id: {}", id);

        User user = userService.getById(id);
        log.info("user: {}", user);

        if (user != null) {
            return Result.success(ResultCode.GET_OK, user);
        } else {
            return Result.error(ResultCode.GET_ERR, "用户查询失败");
        }
    }

    /**
     * 根据ID修改用户
     *
     * @param user
     * @return
     */
    @PutMapping({"/all", "/status"})
    public Result<String> updateUser(@RequestBody User user) {
        log.info("user: {}", user);

        boolean flag = userService.updateById(user);

        if (flag) {
            return Result.success(ResultCode.UPDATE_OK, "用户修改成功");
        } else {
            return Result.error(ResultCode.UPDATE_ERR, "用户修改失败");
        }

    }

    /**
     * 根据名字（非空）查询所有并分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<IPage<User>> page(int page, int pageSize, String name) {
        log.info("page={},pageSize={},name={}", page, pageSize, name);

        // 执行查询
        IPage<User> userIPage = userService.getPage(page, pageSize, name);

        if (userIPage != null) {
            return Result.success(ResultCode.GET_OK, userIPage);
        } else {
            return Result.error(ResultCode.GET_ERR, "用户查询失败");
        }
    }
}
